
package com.es.highLevel;


import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.lucene.analysis.util.ClasspathResourceLoader;
import org.apache.lucene.search.join.ScoreMode;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.client.indices.CreateIndexResponse;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.join.query.HasChildQueryBuilder;
import org.elasticsearch.join.query.HasParentQueryBuilder;
import org.elasticsearch.join.query.JoinQueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.IOException;


/**
 * ES HIGH LEVEL 操作
 */

public class HighLevelClientTest {

    public static void main(String[] args) {
        //createIndex();
        //createSchemaIndex();
        //addData2Index();
        searchIndex();
    }

    /**
     * 查询
     */
    private static void searchIndex(){
        String indexName = "my-index-000001";
        // 获取客户端实例
        RestHighLevelClient client = createClient();
        try {
            SearchRequest request = new SearchRequest(indexName);
            SearchSourceBuilder builder = new SearchSourceBuilder();
            // has_child 查询
            //HasChildQueryBuilder hasChildQueryBuilder = JoinQueryBuilders.hasChildQuery("answer", QueryBuilders.matchAllQuery(), ScoreMode.None);
            //builder.query(hasChildQueryBuilder);

            // has_parent 查询
            HasParentQueryBuilder hasParentQueryBuilder = JoinQueryBuilders.hasParentQuery("question", QueryBuilders.matchAllQuery(), false);
            builder.query(hasParentQueryBuilder);
            builder.from(0);
            builder.size(10);
            request.source(builder);
            SearchResponse response = client.search(request, RequestOptions.DEFAULT);
            SearchHit[] hits = response.getHits().getHits();
            for (SearchHit hit : hits) {
                System.out.println(hit.getSourceAsString());
            }
        }catch (IOException e){
            e.printStackTrace();
        }finally {
            try {
                client.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 添加数据
     */
    private static void addData2Index(){
        String indexName = "my-index-000001";
        // 获取客户端实例
        RestHighLevelClient client = createClient();
        // 准备question测试数据
        JSONObject question = new JSONObject();
        question.put("my_id", "1");
        question.put("text", "This is a question 001");
        JSONObject join = new JSONObject();
        join.put("name", "question");
        question.put("my_join_field", join);
        try {
            IndexRequest request = new IndexRequest(indexName).id("1").source(question.toJSONString(), XContentType.JSON);
            IndexResponse response = client.index(request, RequestOptions.DEFAULT);
            // 打印插入结果
            System.out.println(response.getResult().name());
        }catch (IOException e){
            e.printStackTrace();
        }finally {
            try {
                client.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 创建 mapping 索引
     */
    private static void createSchemaIndex() {
        String indexName = "my-index-000001";
        // 获取客户端实例
        RestHighLevelClient client = createClient();
        try {
            // 读取 classpath 下的 JSON 文件内容
            String file = ClasspathResourceLoader.class.getResource("/mapping/myIndexMapping.json").getFile();
            BufferedInputStream inputStream = new BufferedInputStream(new FileInputStream(file));
            byte[] buffer = new byte[inputStream.available()];
            inputStream.read(buffer);
            String jsonMapping = new String(buffer);
            // 创建索引请求
            CreateIndexRequest request = new CreateIndexRequest(indexName);
            // 设置 schema
            request.source(jsonMapping, XContentType.JSON);
            CreateIndexResponse createIndexResponse = client.indices().create(request, RequestOptions.DEFAULT);
            if (createIndexResponse.isAcknowledged()) {
                System.out.println("成功创建索引：" + indexName);
            } else {
                System.out.println("创建索引失败");
            }
        } catch (IOException e){
            e.printStackTrace();
        }finally {
            try {
                client.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 创建普通索引
     */

    public static void createIndex(){
        String indexName = "index_test";
        // 获取客户端实例
        RestHighLevelClient client = createClient();
        //创建索引请求
        CreateIndexRequest request = new CreateIndexRequest(indexName);
        try {
            CreateIndexResponse createIndexResponse = client.indices().create(request, RequestOptions.DEFAULT);
            if (createIndexResponse.isAcknowledged()) {
                System.out.println("成功创建索引：" + indexName);
            } else {
                System.out.println("创建索引失败");
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            //关闭连接
            try {
                client.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 通过认证连接ES，获取客户端
     */
    public static RestHighLevelClient createClient(){
        String hostname = "192.168.0.67";
        int port = 9200;
        String username = "elastic";
        String password = "1BZTIs85w3fOovvdFodM";
        final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, password));
        RestClientBuilder restClientBuilder = RestClient.builder(new HttpHost(hostname, port))
                .setHttpClientConfigCallback(httpAsyncClientBuilder -> httpAsyncClientBuilder.setDefaultCredentialsProvider(credentialsProvider));
        return new RestHighLevelClient(restClientBuilder);
    }

}

